import router from './router'
import store from './store'
// store.commit('user/SET_CATEGORYLIST', permission)
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css' // 进度条 style
import { hasTokens, isPhone } from '@/utils/auth' // get token from cookie
// import { Message } from 'element-ui'// 引入element的Message插件

import getPageTitle from '@/utils/get-page-title'
// import { resetRouter } from '@/router'

const whiteList = ['/login', '/Phone/login'] // no redirect whitelist
const pcPageList = ['/login']
const hasToken = hasTokens()
if (hasToken) {
  store.commit('user/SET_RESETROUTE')
  store.commit('user/SET_ADDROUTES')
}// 刷新页面后，路由表里会只剩下本地定义的 ，没有登录后添加的，所以这里再处理一下

NProgress.configure({ showSpinner: false }) // 进度条 Configuration

router.beforeEach((to, from, next) => {
  // console.log('从', from.path)
  // console.log('到', to.path)
  const hasToken = hasTokens() // 是否登录
  const isPC = !(isPhone()) // 是否移动端
  // if (isPhone()) {
  //   Message.error('这是移动端')
  // }
  NProgress.start() // 进度条
  document.title = getPageTitle(to.meta.title) // 设置网页标题
  if (hasToken) {
    // console.log('有token')
    store.commit('user/SET_ROLE')
    store.commit('user/SET_USERINFO')
    store.commit('user/SET_ISPC')
    store.commit('user/SET_CATEGORYLIST')
    next()
    NProgress.done()
  } else {
    // console.log('无token')
    if (whiteList.indexOf(to.path) !== -1) {
      store.commit('user/SET_RESETROUTE')
      if (isPC) {
        if (pcPageList.indexOf(to.path) !== -1) {
          console.log('PC ，PC')
          next()
          NProgress.done()
        } else {
          console.log('PC ，APP')
          next(`/login`)
          NProgress.done()
        }
      } else {
        if (pcPageList.indexOf(to.path) !== -1) {
          console.log('APP ，PC')
          next(`/Phone/login`)
          NProgress.done()
        } else {
          next()
          NProgress.done()
          console.log('APP ，APP')
        }
      }
    } else {
      next(`/login`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()// 进度条
})

